import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Progress, Typography, Spin, Tag, Button, Tooltip } from 'antd';
import { 
  AimOutlined, 
  CalendarOutlined, 
  CheckCircleOutlined,
  ClockCircleOutlined,
  TrophyOutlined,
  FireOutlined
} from '@ant-design/icons';
import { statisticsService } from '../services/api';

const { Title, Text } = Typography;

interface Goal {
  id: number;
  goal_type: string;
  goal_name: string;
  target_value: number;
  current_value: number;
  unit: string;
  start_date: string;
  end_date: string;
  is_completed: boolean;
  completed_at: string;
}

const GoalsSection: React.FC = () => {
  const [goals, setGoals] = useState<Goal[]>([]);
  const [loading, setLoading] = useState(false);

  const loadGoals = async () => {
    setLoading(true);
    try {
      const response = await statisticsService.getGoals();
      if ((response as any).success) {
        setGoals((response as any).data);
      }
    } catch (error) {
      console.error('加载学习目标失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadGoals();
  }, []);

  const getGoalTypeText = (type: string) => {
    switch (type) {
      case 'daily':
        return '每日目标';
      case 'weekly':
        return '每周目标';
      case 'monthly':
        return '每月目标';
      default:
        return '目标';
    }
  };

  const getGoalTypeColor = (type: string) => {
    switch (type) {
      case 'daily':
        return '#52c41a';
      case 'weekly':
        return '#1890ff';
      case 'monthly':
        return '#fa8c16';
      default:
        return '#722ed1';
    }
  };

  const getProgressPercent = (current: number, target: number) => {
    if (target === 0) return 0;
    return Math.min(Math.round((current / target) * 100), 100);
  };

  const getDaysRemaining = (endDate: string) => {
    const end = new Date(endDate);
    const now = new Date();
    const diffTime = end.getTime() - now.getTime();
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    return diffDays;
  };

  const getGoalIcon = (type: string) => {
    switch (type) {
      case 'daily':
        return <ClockCircleOutlined style={{ color: '#52c41a' }} />;
      case 'weekly':
        return <CalendarOutlined style={{ color: '#1890ff' }} />;
      case 'monthly':
        return <TrophyOutlined style={{ color: '#fa8c16' }} />;
      default:
        return <AimOutlined style={{ color: '#722ed1' }} />;
    }
  };

  if (loading) {
    return (
      <Card title="学习目标" extra={<AimOutlined />}>
        <div style={{ textAlign: 'center', padding: '20px' }}>
          <Spin size="large" />
        </div>
      </Card>
    );
  }

  return (
    <Card title="学习目标" extra={<AimOutlined />}>
      {goals.length === 0 ? (
        <div style={{ textAlign: 'center', padding: '20px' }}>
          <Text type="secondary">暂无学习目标，设定目标开始努力吧！</Text>
        </div>
      ) : (
        <Row gutter={[16, 16]}>
          {goals.map((goal) => {
            const progress = getProgressPercent(goal.current_value, goal.target_value);
            const daysRemaining = getDaysRemaining(goal.end_date);
            
            return (
              <Col xs={24} lg={12} key={goal.id}>
                <Card
                  size="small"
                  style={{
                    border: goal.is_completed ? '2px solid #52c41a' : '1px solid #d9d9d9',
                    background: goal.is_completed ? '#f6ffed' : '#ffffff'
                  }}
                >
                  <div style={{ marginBottom: '12px' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '8px' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                        {getGoalIcon(goal.goal_type)}
                        <Text strong style={{ color: goal.is_completed ? '#52c41a' : '#1890ff' }}>
                          {goal.goal_name}
                        </Text>
                      </div>
                      <Tag color={getGoalTypeColor(goal.goal_type)}>
                        {getGoalTypeText(goal.goal_type)}
                      </Tag>
                    </div>
                    
                    {goal.is_completed && (
                      <div style={{ display: 'flex', alignItems: 'center', gap: '4px', marginBottom: '8px' }}>
                        <CheckCircleOutlined style={{ color: '#52c41a' }} />
                        <Text style={{ color: '#52c41a', fontSize: '12px' }}>
                          已完成于 {new Date(goal.completed_at).toLocaleDateString()}
                        </Text>
                      </div>
                    )}
                  </div>

                  <div style={{ marginBottom: '12px' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '4px' }}>
                      <Text style={{ fontSize: '12px' }}>
                        进度: {goal.current_value}/{goal.target_value} {goal.unit}
                      </Text>
                      <Text style={{ fontSize: '12px', color: progress >= 100 ? '#52c41a' : '#1890ff' }}>
                        {progress}%
                      </Text>
                    </div>
                    <Progress
                      percent={progress}
                      size="small"
                      strokeColor={goal.is_completed ? '#52c41a' : '#1890ff'}
                      status={goal.is_completed ? 'success' : 'active'}
                    />
                  </div>

                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                      <Text style={{ fontSize: '12px', color: '#8c8c8c' }}>
                        期限: {new Date(goal.end_date).toLocaleDateString()}
                      </Text>
                    </div>
                    
                    <div style={{ textAlign: 'right' }}>
                      {daysRemaining > 0 ? (
                        <Text style={{ fontSize: '12px', color: daysRemaining <= 3 ? '#f50' : '#8c8c8c' }}>
                          剩余 {daysRemaining} 天
                        </Text>
                      ) : (
                        <Text style={{ fontSize: '12px', color: '#f50' }}>
                          已过期
                        </Text>
                      )}
                    </div>
                  </div>
                </Card>
              </Col>
            );
          })}
        </Row>
      )}
    </Card>
  );
};

export default GoalsSection;
